package com.ebraga.trackerclub.android.util;

import java.text.DateFormat;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.ebraga.trackerclub.android.view.receiver.PositionReceiver;
import com.ebraga.trackerclub.android.view.receiver.SyncReceiver;

public class SynchManager {


	private static final String TAG = DLog.logTag(SynchManager.class);

	// Start synch/update service every 15 minutes (in millisec)
	//public static final long INTERVAL_SYNCH = AlarmManager.INTERVAL_FIFTEEN_MINUTES; //1000L * 60 * 15;
	public static final long INTERVAL_GPS = 1000L * 60 * 1;
	public static final long INTERVAL_SYNCH = 1000L * 60 * 2;
	

	protected SynchManager(Context context) {
		//
	}
	
	/**
	 * This method can be called multiple times without risk of duplicating the alarm, 
	 * because it recognizes the alarm receiver. 
	 * @param context
	 */
	public static void setRepeatingAlarmForSynch(Context context, long timeOfFirstAlarm) {
		setRepeatingAlarm(context, timeOfFirstAlarm, INTERVAL_SYNCH, SyncReceiver.class);
	}
	

	/**
	 * This method can be called multiple times without risk of duplicating the alarm, 
	 * because it recognizes the alarm receiver. 
	 * @param context
	 */
	public static void setRepeatingAlarmForPosition(Context context, long timeOfFirstAlarm) {
		setRepeatingAlarm(context, timeOfFirstAlarm, INTERVAL_GPS,  PositionReceiver.class);
	}	
	
	/**
	 * This method can be called multiple times without risk of duplicating the alarm, 
	 * because it recognizes the alarm receiver. 
	 * 
	 * @param context
	 * @param timeOfFirstAlarm
	 * @param timeInterval
	 */
	private static void setRepeatingAlarm(Context context, long timeOfFirstAlarm, long timeInterval, Class<?> receiverClass) {
		
		DLog.d(TAG, "setRepeatingAlarmForSynch - timeOfFirstAlarm: " + DateFormat.getDateTimeInstance().format(timeOfFirstAlarm));
		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

		Intent synchIntent = new Intent(context, receiverClass);
		PendingIntent synchPIntent = PendingIntent.getBroadcast(context, 0, synchIntent,
									PendingIntent.FLAG_UPDATE_CURRENT);
		// InexactRepeating allows Android to optimize the energy consumptionPo
		alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeOfFirstAlarm, timeInterval, synchPIntent);		
		
	}	
	
	
}
